package cn.touna.jss.common.aspect;

import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.risk.threadpool.common.util.ThreadPoolUtil;
import com.touna.loan.log.service.TracerContextUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * \* User: MeiZhongHao
 * \* Date: 2018-06-08
 * \* Time: 10:59
 * \* Description: ApiMapping Aspect Method
 * \       主要功能，判断是否取存缓存，判断是的存储接口请求历史
 */
@Component
@Aspect
public class ApiMappingAspect {

    private static final Logger logger = LogManager.getLogger(ApiMappingAspect.class);

    @Autowired
    private ApiMappingCacheService apiMappingCacheService;
    @Autowired
    private ApiMappingRecordService apiMappingRecordService;

    @Pointcut("@annotation(cn.touna.jss.modules.adapter.ApiMapping)")
    private void checkPointCutMethod() {
    }

    @Around("checkPointCutMethod() && @annotation(apiMapping)")
    public Object audit(ProceedingJoinPoint pjp,ApiMapping apiMapping) throws Throwable {
        // 存取缓存
        return apiMappingCacheService.audit(pjp,apiMapping);
    }

    @AfterReturning(pointcut = "checkPointCutMethod()", returning = "result")
    public void doAfterReturning(JoinPoint point,Object result) throws Throwable{
        // 储存请求记录
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes == null ? null : attributes.getRequest();
        ThreadPoolUtil.submit("jss-pool-name", TracerContextUtil.getTraceId(), apiMappingRecordService, "saveHistory", point, result, request);
    }
}